<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 90%; margin-left:50px;">
      <el-row :gutter="40">
        <el-col :span="20">
          <el-form-item label="脱敏名称" prop="maskName">
            <el-input v-model="temp.maskName" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="状态" prop="status" >
            <el-radio
              disabled
              v-for="item in dictList('is_use')"
              :key="'type' + item.label"
              v-model="temp.status"
              :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="数据API" prop="apiId">
            <el-select v-model="temp.apiId" placeholder="请选择数据API" disabled>
              <el-option
                v-for="api in apiOptions"
                :key="api.id"
                :label="api.apiName"
                :value="api.id"
                :disabled="api.status === '0'"
              />
            </el-select>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="脱敏规则" prop="configJson">
<!--            <el-select v-model="temp.configJson" class="filter-item" placeholder="请选择脱敏规则" >-->
<!--              <el-option-->
<!--                v-for="item in dictList('desensitization_rules')"-->
<!--                :key="'type' + item.label"-->
<!--                :label="item.label"-->
<!--                :value="item.value" />-->
<!--            </el-select>-->
            <el-table
              :data="resParamList"
              stripe
              border
              :max-height="300"
              style="width: 100%;"
            >
              <el-table-column label="序号" width="55" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.$index +1 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="fieldName" label="字段名称" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row.fieldName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="fieldComment" label="描述" align="center" show-overflow-tooltip />
              <el-table-column prop="dataType" label="数据类型" align="center" show-overflow-tooltip />
              <el-table-column prop="exampleValue" label="示例值" align="center" show-overflow-tooltip />
              <el-table-column prop="cipherType" label="脱敏类型" align="center" >
                <template slot-scope="scope">
                  <span>{{ scope.row.cipherType | dictLabel('data_cipher_type') }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="cryptType" label="规则类型" align="center" show-overflow-tooltip >
                <template slot-scope="scope">
                  <span>{{ scope.row.cryptType | getDictLabel1(scope.row.cipherType) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="temp.remark" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        {{ $t('table.cancel') }}
      </el-button>
<!--      <el-button type="primary" :loading="loading" @click="dialogStatus==='create'?createData():updateData()">-->
<!--        {{ $t('table.confirm') }}-->
<!--      </el-button>-->
    </div>
    <!-- 脱敏规则对话框 -->
    <el-dialog :title="cipher.title" :visible.sync="cipher.open" width="400px" append-to-body>
      <el-form ref="dataform2" :model="temp2" :rules="rules2" label-width="80px">
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="temp2.fieldName" placeholder="请输入字段名称" disabled/>
        </el-form-item>
        <el-form-item label="脱敏类型" prop="cipherType">
          <el-select v-model="temp2.cipherType" clearable placeholder="请选择脱敏类型" @change="cipherTypeSelectChanged" disabled>
            <el-option
              v-for="item in cipherTypeOptions"
              :key="'type' + item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型" prop="cryptType">
          <el-select v-model="temp2.cryptType" clearable placeholder="请选择规则类型" disabled>
            <el-option
              v-for="item in cryptTypeOptions"
              :key="'type' + item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
<!--        <el-button type="primary" @click="submitFieldCipherForm">确 定</el-button>-->
        <el-button @click="cipher.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { createMarketApiMask, updateMarketApiMask, getMarketApiMask } from '@/api/marketapimask/marketApiMask'
import { fetchMarketApiList,getMarketApi } from '@/api/marketApi/marketApi'
import { getDictLabel, getDictList } from '@/utils/dict'

export default {
  name: 'MarketApiMaskInfo',
  data() {
    return {
      rules: {
        maskName: [{ required: true, message: '脱敏名称为必填项', trigger: 'blur' }],
                          status: [{ required: true, message: '状态为必填项', trigger: 'blur' }],
                          apiId: [{ required: true, message: '数据API为必填项', trigger: 'blur' }]
                        },
      rules2: {
        fieldName: [
          { required: true, message: '字段名称不能为空', trigger: 'blur' }
        ]
      },
      temp: {},
      temp2: {
        fieldName: undefined,
        cipherType: undefined,
        cryptType: undefined
      },
      textMap: {
        info: '详情'
      },
      // 数据API数据字典
      apiOptions: [],
      // 脱敏字段信息
      resParamList: [],
      id: undefined,
      // 脱敏类型数据字典
      cipherTypeOptions: getDictList('data_cipher_type'),
      cryptTypeOptions: [],
      // 正则替换数据字典
      regexCryptoOptions: getDictList('data_regex_crypto'),
      // 加密算法数据字典
      algorithmCryptoOptions: getDictList('data_algorithm_crypto'),
      timer: '',
      cipher: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '脱敏规则配置'
      },
      loading: false,
      dialogFormVisible: false,
      dialogStatus: ''
    }
  },

  methods: {
    getList() {
      this.$emit('refreshList')
    },
    resetTemp() {
      this.loading = false
      this.temp = {
        id: undefined,
              maskName: undefined,
              status: '1',
              apiId: undefined,
              rules: [],
              remark: undefined
            }
    },
    getDataApiList() {
      fetchMarketApiList().then(response => {
        if (response.data.code === 0) {
          this.apiOptions = response.data.data
        }
      })
    },
    apiSelectChanged(val) {
      getMarketApi(val).then(response => {
        if (response.data.code === 0) {
          this.resParamList = response.data.data.resParams
        }
      })
    },
    fieldRule(fieldName) {
      this.cipher.open = true
      this.temp2.fieldName = fieldName
      this.temp2.cipherType = undefined
      this.temp2.cryptType = undefined
      this.cryptTypeOptions = []
    },
    cipherTypeSelectChanged(val) {
      this.temp2.cryptType = undefined
      this.cryptTypeOptions = []
      if (val === '1') {
        // 正则替换
        this.cryptTypeOptions = this.regexCryptoOptions
      } else if (val === '2') {
        // 加密算法
        this.cryptTypeOptions = this.algorithmCryptoOptions
      }
    },
    submitFieldCipherForm() {
      const fieldRuleIndex = this.temp.rules.findIndex((item) => {
        return item.fieldName === this.temp2.fieldName
      })
      if (fieldRuleIndex !== -1) {
        // 当返回-1时，则说明数组中没有
        this.temp.rules.splice(fieldRuleIndex, 1)
      }
      if (this.temp2.cipherType && this.temp2.cryptType) {
        this.temp.rules.push(this.temp2)
      }
      const cipher = this.cipherTypeOptions.find((item) => {
        return item.value === this.temp2.cipherType
      })
      const crypt = this.cryptTypeOptions.find((item) => {
        return item.value === this.temp2.cryptType
      })
      const fieldParamIndex = this.resParamList.findIndex((item) => {
        return item.fieldName === this.temp2.fieldName
      })
      const resParam = Object.assign({}, this.resParamList[fieldParamIndex], { cipherType: (cipher && cipher.value) || undefined, cryptType: (crypt && crypt.value) || undefined })
      this.$set(this.resParamList, fieldParamIndex, resParam)
      this.cipher.open = false
    },
    /** 获取详情 */
    async getApiMask(id) {
      const dataApiMask = await getMarketApiMask(id).then(response => {
        if (response.data.code === 0) {
            return response.data.data
          }
      }) || {}
        const dataApi = await getMarketApi(dataApiMask.apiId).then(response => {
          if (response.data.code === 0) {
            return response.data.data
        }
        }) || {}
        if (dataApi && dataApi.resParams.length > 0) {
          this.resParamList = dataApi.resParams
          dataApiMask.rules.forEach(rule => {
            const fieldParamIndex = this.resParamList.findIndex((param) => {
              return param.fieldName === rule.fieldName
            })
            if (fieldParamIndex !== -1) {
              const cipher = this.cipherTypeOptions.find((item) => {
                return item.value === rule.cipherType
              })
              let crypt = {}
              if (rule.cipherType === '1') {
                crypt = this.regexCryptoOptions.find((item) => {
                  return item.value === rule.cryptType
                })
              } else if (rule.cipherType === '2') {
                crypt = this.algorithmCryptoOptions.find((item) => {
                  return item.value === rule.cryptType
                })
              }
              const resParam = Object.assign({}, this.resParamList[fieldParamIndex], { cipherType: (cipher && cipher.value) || undefined, cryptType: (crypt && crypt.value) || undefined })
              this.$set(this.resParamList, fieldParamIndex, resParam)
            }
          })
        }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.resParamList = []
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()

      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.rules.length <= 0) {
            this.$message.error('脱敏字段规则配置不能为空')
            return
          }
          this.loading = true
          createMarketApiMask(this.temp).then(response => {
            this.loading = false
            if (response.data.code === 0) {
              this.getList()
              this.dialogFormVisible = false
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    },
    handleInfo(id) {
      this.resetTemp()
      this.getDataApiList()
      this.dialogStatus = 'info'
      this.dialogFormVisible = true
      this.resParamList = []
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // getMarketApiMask(id).then(response => {
      //   if (response.data.code === 0) {
      //     this.temp = response.data.data
      //   } else {
      //     this.dialogFormVisible = false
      //     this.$message.error(response.data.msg)
      //   }
      // })
      this.getApiMask(id)
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.rules.length <= 0) {
            this.$message.error('脱敏字段规则配置不能为空')
            return
          }
          this.loading = true
          updateMarketApiMask(this.temp).then(response => {
            this.loading = false
            if (response.data.code === 0) {
              this.dialogFormVisible = false
              this.getList()
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
